package com.beiing.tianshuai.tianshuai.mine.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.activity.SinglePicPreviewActivity;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseFragment;
import com.beiing.tianshuai.tianshuai.entity.FollowResultBean;
import com.beiing.tianshuai.tianshuai.entity.PersonalInfoBean;
import com.beiing.tianshuai.tianshuai.mine.presenter.MinePresenter;
import com.beiing.tianshuai.tianshuai.mine.view.MineViewImpl;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;
import com.beiing.tianshuai.tianshuai.widget.CircleImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import butterknife.BindView;

/**
 * 我的界面
 *
 * @author Jinda Yang
 * @date 2017/7/6
 */

public class MineFragment extends BaseFragment implements MineViewImpl {

    private static final String TAG = "MineFragment";
    private Context mContext;
    private MinePresenter mPresenter;


    /**
     * toolbar
     */
    @BindView(R.id.toolbar)
    Toolbar mToolbar;

    /**
     * 测试选项
     */
    @BindView(R.id.btn_my_test)
    TextView mBtnTest;

    /**
     * 用户头像部分
     */
    @BindView(R.id.rl_user_head)
    RelativeLayout mRlUserHead;

    /**
     * 认证标识
     */
    @BindView(R.id.civ_identification_sign)
    CircleImageView mIdentificationSign;

    /**
     * 用户头像
     */
    @BindView(R.id.civ_mine_avatar)
    CircleImageView mAvatar;

    /**
     * 签名
     */
    @BindView(R.id.txt_mine_sign)
    TextView mSign;

    /**
     * 用户昵称
     */
    @BindView(R.id.txt_mine_nickname)
    TextView mNickName;

    /**
     * 标题
     */
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTitle;

    /**
     * 全部订单
     */
    @BindView(R.id.tv_my_order)
    TextView mAllOrder;

    /**
     * 个人认证
     */
    @BindView(R.id.btn_my_identification)
    TextView mIdentification;

    /**
     * 我关注的
     */
    @BindView(R.id.tv_my_followed)
    TextView mAttention;

    /**
     * 我的投稿
     */
    @BindView(R.id.tv_my_publish)
    TextView mPublish;

    /**
     * 我的收藏
     */
    @BindView(R.id.tv_my_collection)
    TextView mCollection;

    /**
     * 反馈吐槽
     */
    @BindView(R.id.btn_my_feedback)
    TextView mFeedBack;

    /**
     * 发布审核
     */
    @BindView(R.id.btn_my_interest)
    TextView mBtnInterest;

    /**
     * 个人主页
     */
    @BindView(R.id.btn_my_zone)
    TextView mBtnZone;

    /**
     * 设置
     */
    @BindView(R.id.btn_settings)
    ImageButton mBtnSettings;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void init(View mView) {
        setHasOptionsMenu(true);
        mContext = getActivity();
        //隐藏的测试按钮
        mBtnTest.setVisibility(View.GONE);
        initStatusBar();
        initToolbar();
        initListener();
        initPresenter();
        isLogin();
    }

    /**
     * 初始化状态栏
     */
    private void initStatusBar() {
        QMUIStatusBarHelper.setStatusBarLightMode(getActivity());
//        int statusBarHeight = QMUIStatusBarHelper.getStatusbarHeight(mContext);
//        mToolbar.setPadding(0, statusBarHeight, 0, 0);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getActivity() != null) {
            ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);
        }
    }

    private void initToolbar() {
        mToolbar.setTitle("");
        mToolbarTitle.setText("我的");
    }

    /**
     * 初始化监听事件
     */
    private void initListener() {
        // 测试按钮
        mBtnTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(mContext, OrderAddressChooseActivity.class);
                startActivity(intent);
            }
        });

        // 个人主页
        mBtnZone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin()) {
                    Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                    intent.putExtra("uid", com.beiing.tianshuai.tianshuai.entity.UserInfoBean.getUid(mContext));
                    mContext.startActivity(intent);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(intent);
                }
            }
        });

        // 我的投稿
        mPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin()) {
                    Intent intent = new Intent(mContext, PersonalPublishActivity.class);
                    intent.putExtra("uid", com.beiing.tianshuai.tianshuai.entity.UserInfoBean.getUid(mContext));
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 我的兴趣
        mBtnInterest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin()) {
                    Intent intent = new Intent(mContext, MyAuditActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 个人认证
        mIdentification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLogin()) {
                    Intent intent = new Intent(mContext, IdentificationActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(intent);
                }
            }
        });

        // 头像部分
        mRlUserHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLogin()) {
                    Intent intent = new Intent(mContext, PersonalInformationActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(intent);
                }
            }
        });

        // 头像
        mAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                press();
                if (isLogin()) {
                    Intent intent = new Intent(mContext, SinglePicPreviewActivity.class);
                    intent.putExtra("avatarUrl", HttpRequestConstant.USER_PIC_HEAD + com.beiing.tianshuai.tianshuai.entity.UserInfoBean.getAvatar(mContext));
                    mContext.startActivity(intent);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(intent);
                }
            }
        });

        // 全部订单
        mAllOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLogin()) {
                    Intent intent = new Intent(mContext, MyOrderActivity.class);
                    intent.putExtra("type", 0);
                    startActivity(intent);
                } else {
                    toLogin();
                }
            }
        });

        // 我关注的
        mAttention.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLogin()) {
                    Intent intent = new Intent(mContext, FansAndIdolActivity.class);
                    intent.putExtra("toUid", com.beiing.tianshuai.tianshuai.entity.UserInfoBean.getUid(mContext));
                    startActivity(intent);
                } else {
                    toLogin();
                }
            }
        });

        // 我的收藏
        mCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLogin()) {
                    Intent intent = new Intent(mContext, MyCollectionActivity.class);
                    intent.putExtra("uid", com.beiing.tianshuai.tianshuai.entity.UserInfoBean.getUid(mContext));
                    startActivity(intent);
                } else {
                    toLogin();
                }
            }
        });

        // 反馈吐槽
        mFeedBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, FeedBackActivity.class);
                startActivity(intent);
            }
        });

        // 设置
        mBtnSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, SettingsActivity.class);
                startActivity(intent);
            }
        });
    }

//    /**
//     * 人为制造的异常
//     */
//    public void press(){
//        int i = 1/0;
//    }

    private void initPresenter() {
        mPresenter = new MinePresenter(this);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            QMUIStatusBarHelper.setStatusBarLightMode(getActivity());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isLogin()) {
            mPresenter.getPersonalInfoResult(com.beiing.tianshuai.tianshuai.entity.UserInfoBean.getUid(mContext));
        } else {
            initUserInfo();
        }
    }

    /**
     * 初始化登陆状态下的用户信息
     */
    private void initUserInfo(PersonalInfoBean bean) {
        // 加载头像
        PersonalInfoBean.DataBean.UserInfoBean userInfo = bean.getData().getUserinfor().get(0);
        String photo = userInfo.getPhoto();
        String name = userInfo.getName();
        LogUtils.i(userInfo.toString(), TAG);
        SPUtils.put(mContext, "uid", userInfo.getUid());
        SPUtils.put(mContext, "sex", userInfo.getSex());
        SPUtils.put(mContext, "photo", photo);
        SPUtils.put(mContext, "avatar" + userInfo.getUid(), photo);
        SPUtils.put(mContext, "tel", userInfo.getTel());
        SPUtils.put(mContext, "status", userInfo.getStatus());
        SPUtils.put(mContext, "name", name);
        SPUtils.put(mContext, "email", userInfo.getEmail());
        SPUtils.put(mContext, "unit", userInfo.getUnit());
        SPUtils.put(mContext, "sign", userInfo.getSign());
        SPUtils.put(mContext, "pass", userInfo.getPass());
        SPUtils.put(mContext, "identification_status", userInfo.getAttestaction());
        // 设置头像
        RequestOptions requestOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .override(350, 350);
        Glide.with(mContext.getApplicationContext())
                .load(TextUtils.isEmpty(photo) ? R.drawable.default_avatar : HttpRequestConstant.USER_PIC_HEAD + photo)
                .apply(requestOptions)
                .into(mAvatar);
        // 设置昵称
        mNickName.setText(name);
        // 设置签名
        mSign.setText(TextUtils.isEmpty(userInfo.getUnit()) ? "[未设置学校]" : userInfo.getUnit());
        // 设置用户认证标识
        switch (userInfo.getAttestaction()) {
            case "2":
                mIdentificationSign.setImageResource(R.mipmap.grrz_icon);
                mIdentificationSign.setVisibility(View.VISIBLE);
                break;
            case "3":
                mIdentificationSign.setImageResource(R.mipmap.strz_icon);
                mIdentificationSign.setVisibility(View.VISIBLE);
                break;
            case "4":
                mIdentificationSign.setImageResource(R.mipmap.qyrz_icon);
                mIdentificationSign.setVisibility(View.VISIBLE);
                break;
            default:
                mIdentificationSign.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 初始化未登陆状态下的用户信息
     */
    private void initUserInfo() {
        // 设置头像
        RequestOptions requestOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .override(350, 350);
        Glide.with(mContext.getApplicationContext())
                .load(R.mipmap.default_avatar)
                .apply(requestOptions)
                .into(mAvatar);
        // 设置昵称
        mNickName.setText("未登录");
        // 设置签名
        mSign.setText("点我去登录噢~");
        mIdentificationSign.setVisibility(View.GONE);
    }

    public boolean isLogin() {
        String uid = SPUtils.getString(mContext, "uid", null);
        return !TextUtils.isEmpty(uid);
    }

    private void toLogin() {
        Intent intent = new Intent(mContext, LoginActivity.class);
        startActivity(intent);
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onRequestSuccess(PersonalInfoBean bean) {
        initUserInfo(bean);
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        LogUtils.e(throwable.toString(), TAG);
        mPresenter.getPersonalInfoResult(com.beiing.tianshuai.tianshuai.entity.UserInfoBean.getUid(mContext));
    }

    @Override
    public void isFollowed(boolean isFollowed) {

    }

    @Override
    public void getFollowResult(FollowResultBean bean) {

    }
}
